package com.zy.mc_module.ui.shortvideo;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseViewHolder;
import com.zy.mc_module.R;
import com.zy.mc_module.base.App;
import com.zy.mc_module.base.BaseActivity;
import com.zy.mc_module.base.BaseFragment;
import com.zy.mc_module.mvp.bean.ShortVideoBean;
import com.zy.mc_module.ui.shortvideo.adapter.LittleVideoAdapter;
import com.zy.mc_module.ui.shortvideo.widget.LoopVideoPlayer;
import com.zy.mc_module.utils.AppTools;
import com.zy.mc_module.utils.StatusBarUtil;
import com.zy.mc_module.utils.StringsUtils;
import com.zy.mc_module.utils.ToastUtil;
import com.zy.mc_module.view.JZMediaExo;
import com.zy.mc_module.utils.retrofit.error.ThdException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import cn.jzvd.JZDataSource;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;

import static cn.jzvd.Jzvd.STATE_NORMAL;
import static cn.jzvd.Jzvd.STATE_PAUSE;
import static cn.jzvd.Jzvd.STATE_PLAYING;

/**
 * @author 几圈年轮
 */
public class ShortVideoFragment extends BaseFragment<VideoContract.View, VideoPresenter> implements PagerLayoutManager.OnPageChangedListener, VideoContract.View {

    /**
     * 预加载条目数
     */
    private static final int DEFAULT_PRELOAD_NUMBER = 5;

    @BindView(R.id.srf_video_list)
    SwipeRefreshLayout mRefreshView;
    @BindView(R.id.rv_little_video)
    RecyclerView mRvLittleVideo;

    private LittleVideoAdapter mLittleVideoAdapter;
    private PagerLayoutManager mPagerLayoutManager;
    private int mCurrentPosition;
    LoopVideoPlayer txvVideo;

    /**
     * 是否正在加载数据
     */
    private boolean isLoadingData = false;
    /**
     * 是否加载完毕
     */
    private boolean isEnd;
    /**
     * 是否是最后视频位置
     */
    private int mLastStopPosition;
    /**
     * 数据请求是否为加载更多数据
     */
    private boolean isLoadMoreData = false;
    /**
     * 请求视频内容页下标
     */
    private int mLastProductIndex;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_short_video;
    }

    @Override
    protected void isLoadSir(Object... objects) {
        super.isLoadSir(false,R.id.srf_video_list);
    }
    @Override
    protected VideoPresenter createPresenter() {
        return new VideoPresenter();
    }

    @Override
    public void initView(Bundle bundle) {
        StatusBarUtil.setStatusTranslucent(this.getActivity());
        txvVideo = new LoopVideoPlayer(context);
        txvVideo.setPlay(() -> {
            BaseViewHolder viewHolder = (BaseViewHolder) mRvLittleVideo.findViewHolderForLayoutPosition(mCurrentPosition);
            if (viewHolder != null) {
                ImageView mVideoThumb = viewHolder.getView(R.id.iv_thumb_item);
                if (mVideoThumb != null) {
                    mVideoThumb.setVisibility(View.INVISIBLE);
                }
            }
        });
        initData();
    }

    private void initData() {
        mPagerLayoutManager = new PagerLayoutManager(context);
        mPagerLayoutManager.setOnPageChangedListener(this);

        mRvLittleVideo.setLayoutManager(mPagerLayoutManager);

        mLittleVideoAdapter = new LittleVideoAdapter(context, presenter);
        mRvLittleVideo.setAdapter(mLittleVideoAdapter);

        requestNewData();
        mLittleVideoAdapter.setOnItemChildClickListener((adapter, view, pos) -> {
            ShortVideoBean bean = mLittleVideoAdapter.getItem(pos);
            if (bean == null) return;
            switch (view.getId()) {
                case R.id.input_tv_seemsg: {
                    //CommentListDialog.newInstance(bean.getArticleId() + "").show(getSupportFragmentManager());
                    break;
                }
                case R.id.input_rl_share: {
                    AppTools.type = 3;
                    AppTools.shareId = bean.getArticleId() + "";
//                    new CommonDialog(this, R.layout.dialog_share, Constant.shares, position -> {
//                        ShareUtil.share(this, Constant.find_url + bean.getArticleId() + "&h5AppuserId=" + UserUtils.getUid(),
//                                bean.getTitle(), AppTools.cutText(Html.fromHtml(bean.getContent()).toString().trim(), 40), bean.getCover(), position);
//                    }).show();
                    break;
                }
                case R.id.video_detail_recommend_shop: {
                    List<String> goodIdList = new ArrayList<>();
                    String goodIds = mLittleVideoAdapter.getData().get(pos).getGoodsId();
                    if (!StringsUtils.isEmpty(goodIds)) {
                        goodIdList.addAll(Arrays.asList(goodIds.split(",")));
                    }
                    if (!StringsUtils.isEmpty(goodIdList)) {
                        //presenter.appSellerShopList(context, 1, "", "", "", goodIdList);
                    }
                    break;
                }
            }
        });
    }

    /**
     * 设置数据刷新监听,回归初始状态
     */
    @Override
    public void initListener() {
        mRefreshView.setOnRefreshListener(() -> {
            isLoadMoreData = false;
            mLastProductIndex = 0;
            page = 1;
            requestNewData();
        });
    }

    @Override
    protected void LazyLoad() {

    }

    @Override
    public void onPause() {
        super.onPause();
        if (txvVideo != null) {
            if (txvVideo.state == STATE_PLAYING) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        txvVideo.startButton.callOnClick();
                    }
                }, 300);
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden){
            if (txvVideo != null) {
                if (txvVideo.state == STATE_PLAYING) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            txvVideo.startButton.callOnClick();
                        }
                    }, 300);
                }
            }
        }else {
            if (txvVideo != null) {
                if (txvVideo.state == STATE_PAUSE || txvVideo.state == STATE_NORMAL) {
                    txvVideo.startButton.callOnClick();
                }
            }
        }
    }

    @Override
    public void onError(ThdException error) {

    }

    /**
     * 数据请求
     */
    private void requestNewData() {
        if (!isLoadMoreData) {
            mRefreshView.setRefreshing(true);
        }

        isLoadingData = true;
        //presenter.getShortVideo(this, page);
        // 模拟网络请求，0.3秒后进行数据返回
        //Log.e("PageIndex", String.valueOf(mLastProductIndex));
        //mHandler.sendEmptyMessageDelayed(0, 300);
        List<ShortVideoBean> shortVideoBeans = new ArrayList<>();
        ShortVideoBean bean = new ShortVideoBean();
        bean.setVideoUrl("https://aweme.snssdk.com/aweme/v1/play/?video_id=374e166692ee4ebfae030ceae117a9d0&line=0&ratio=720p&media_type=4&vr_type=0");
        bean.setArticleId(1);
        bean.setTitle("abc");
        bean.setContent("abcd");
        shortVideoBeans.add(bean);
        shortVideoBeans.add(bean);
        shortVideoBeans.add(bean);
        shortVideoBeans.add(bean);
        shortVideoBeans.add(bean);
        shortVideoBeans.add(bean);
        shortVideoBeans.add(bean);
        onVideoListUpdate(shortVideoBeans);
    }

    /**
     * 数据更新
     *
     * @param videoList 网络回调获取数据
     */
    public void onVideoListUpdate(List<ShortVideoBean> videoList) {
        isEnd = videoList == null || videoList.size() < 10;
        isLoadingData = false;
        if (mRefreshView != null && mRefreshView.isRefreshing()) {
            mRefreshView.setRefreshing(false);
        }
        if (videoList == null) {
            return;
        }
        mLastProductIndex += videoList.size();
        if (isLoadMoreData) {
            // 加载更多数据
            if (mLittleVideoAdapter != null) {
                mLittleVideoAdapter.addData(videoList);
            }
        } else {
            // 刷新数据
            //isEnd = false;
            mLittleVideoAdapter.setNewData(videoList);
        }
    }

    /**
     * 初始化加载完成,进行视频播放
     */
    @Override
    public void onPageInitComplete() {
        int position = mPagerLayoutManager.findFirstVisibleItemPosition();
        if (position != -1) {
            mCurrentPosition = position;
        }

        // 预加载，请求数据内容
        int itemCount = mLittleVideoAdapter.getItemCount();
        //if (itemCount - position < DEFAULT_PRELOAD_NUMBER && !isLoadingData && !isEnd) {
        //    requestNewData();
        //}
        startPlay(mCurrentPosition);

        mLastStopPosition = -1;
    }

    /**
     * 页面脱离，内容释放
     *
     * @param position 子布局在RecyclerView位置
     * @param isNext   是否有下一个
     */
    @Override
    public void onPageRelease(int position, boolean isNext) {
        if (mCurrentPosition == position) {
            mLastStopPosition = position;
            stopPlay();
            BaseViewHolder viewHolder = (BaseViewHolder) mRvLittleVideo.findViewHolderForLayoutPosition(mCurrentPosition);
            if (viewHolder != null) {
                ImageView mVideoThumb = viewHolder.getView(R.id.iv_thumb_item);
                if (mVideoThumb != null) {
                    mVideoThumb.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    /**
     * 页面附着，内容展示
     *
     * @param position 子布局在RecyclerView位置
     * @param isLast   是否最后一个
     */
    @Override
    public void onPageSelected(int position, boolean isLast) {
        if (mCurrentPosition == position && mLastStopPosition != position) {
            return;
        }

        // 预加载，请求数据内容
        int itemCount = mLittleVideoAdapter.getItemCount();
        if (itemCount - position < DEFAULT_PRELOAD_NUMBER && !isLoadingData && !isEnd) {
            // 正在加载中, 防止网络太慢或其他情况造成重复请求列表
            page++;
            isLoadMoreData = true;
            isLoadingData = true;
            requestNewData();
        }
        if (itemCount == position + 1 && isEnd) {
            Toast.makeText(context, "暂无更多内容~", Toast.LENGTH_SHORT).show();
        }
        startPlay(position);
        mCurrentPosition = position;
    }

    /**
     * 停止播放，移除视图
     */
    private void stopPlay() {

        ViewParent parent = txvVideo.getParent();
        if (parent instanceof FrameLayout) {
            ((FrameLayout) parent).removeView(txvVideo);
        }
    }

    @Override
    public void onDestroy() {
        Jzvd.releaseAllVideos();
        super.onDestroy();
    }

    /**
     * 开始播放视频内容，进行播放器视图加载
     */
    private void startPlay(int position) {
        if (position < 0 || position >= mLittleVideoAdapter.getData().size()) {
            return;
        }
        ViewParent parent = txvVideo.getParent();
        if (parent instanceof FrameLayout) {
            ((ViewGroup) parent).removeView(txvVideo);
        }
        String url = mLittleVideoAdapter.getData().get(position).getVideoUrl();
        LinkedHashMap map = new LinkedHashMap();

        String proxyUrl = App.getProxy(context).getProxyUrl(url);

        map.put("高清", proxyUrl);
//        map.put("标清", VideoConstant.videoUrls[0][6]);
//        map.put("普清", VideoConstant.videoUrlList[0]);
        JZDataSource jzDataSource = new JZDataSource(map, "");
        jzDataSource.looping = true;
        jzDataSource.currentUrlIndex = 0;
        txvVideo.setUp(jzDataSource, JzvdStd.SCREEN_NORMAL, JZMediaExo.class);
        BaseViewHolder holder = (BaseViewHolder) mRvLittleVideo.findViewHolderForLayoutPosition(position);
        if (holder != null) {
            FrameLayout mVideoContent = holder.getView(R.id.fl_content_item);
            mVideoContent.addView(txvVideo, 0);
            txvVideo.startVideo();

        }
    }

    public static List<String> makeData() {
        List<String> urlList = new ArrayList<>();
        //urlList.add("http://swy-mall.oss-cn-beijing.aliyuncs.com/APP/-1/2021-05/19/202105139132954358153.mp4");//http://swy-mall.oss-cn-beijing.aliyuncs.com/APP/-1/2021-05/19/202105139133000495152.jpg
        //urlList.add("http://swy-mall.oss-cn-beijing.aliyuncs.com/APP/-1/2021-05/18/202105138191648698001.mp4");//http://swy-mall.oss-cn-beijing.aliyuncs.com/APP/-1/2021-05/18/202105138191653975852.jpg
        //urlList.add("https://oss.swy.315bzsc.com/video/20210512-bjgjzlhzqzhy.MP4");//http://swy-mall.oss-cn-beijing.aliyuncs.com/APP/-1/2021-05/12/202105132205725466302.png
        //urlList.add("https://oss.swy.315bzsc.com/video/20210512-bjgjzlhzhyhzzf.MP4");//http://swy-mall.oss-cn-beijing.aliyuncs.com/APP/-1/2021-05/12/202105132205603524654.png
        //urlList.add("https://oss.swy.315bzsc.com/video/20210512-bjgjzlhzhy.mp4");//http://swy-mall.oss-cn-beijing.aliyuncs.com/APP/-1/2021-05/12/202105132205450486306.png
        //urlList.add("https://oss.swy.315bzsc.com/video/20210512-swygqcdh.mp4");//http://swy-mall.oss-cn-beijing.aliyuncs.com/APP/-1/2021-05/12/202105132205115361826.png
        //urlList.add("https://oss.swy.315bzsc.com/video/20210512-2018dws.mp4");//http://swy-mall.oss-cn-beijing.aliyuncs.com/APP/-1/2021-05/12/202105132182204680937.png
        //urlList.add("https://aweme.snssdk.com/aweme/v1/play/?video_id=374e166692ee4ebfae030ceae117a9d0&line=0&ratio=720p&media_type=4&vr_type=0");
        return urlList;
    }

}
